package com.ruoyi.consumer.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ijpay.core.kit.WxPayKit;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.consumer.aop.annotation.RecordOpeate;
import com.ruoyi.consumer.controller.facilit.fill.FillService;
import com.ruoyi.consumer.controller.wallet.RefundService;
import com.ruoyi.consumer.domain.CFillingFacilit;
import com.ruoyi.consumer.domain.CUnitPrice;
import com.ruoyi.consumer.domain.CUser;
import com.ruoyi.consumer.domain.order.PayOrderDTO;
import com.ruoyi.consumer.domain.pay.JsApiOrderModel;
import com.ruoyi.consumer.service.impl.CFillingFacilitServiceImpl;
import com.ruoyi.consumer.service.impl.CUnitPriceServiceImpl;
import com.ruoyi.consumer.service.impl.CUserServiceImpl;
import com.ruoyi.consumer.utils.pay.OrderNumberGenerator;
import com.ruoyi.consumer.utils.pay.Payment;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

import static com.ruoyi.consumer.utils.pay.Payment.generateRandomString;

@RestController
@Api(tags = "微信支付")
@RequestMapping("/api/pay")
public class PayController {

    @Autowired
    private CFillingFacilitServiceImpl facilitService;

    @Autowired
    private CUnitPriceServiceImpl cUnitPriceService;

    @Autowired
    private CUserServiceImpl cUserService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RefundService refundService;

    @Autowired
    private FillService fillService;

    @ApiOperation("扫码加注,预订单")
    @PostMapping("/to")
    public AjaxResult to(@ApiParam(value = "userOpenid", required = true) String userOpenid,
                         @ApiParam(value = "支付金额", required = true) String orderMoney,
                         @ApiParam(value = "设备Id", required = true) String facilitId,
                         @ApiParam(value = "设备号", required = true) String snNumber) {

        //查询用户是否存在
        CUser cUser = new CUser();
        cUser.setOpenid(userOpenid);
        List<CUser> cUsers = cUserService.selectCUserList(cUser);
        Assert.notNull(cUsers, "用户不存在");

        //查询设备信息
        CFillingFacilit cFillingFacilit = facilitService.selectCFillingFacilitByFacilitId(Integer.valueOf(facilitId));
        Assert.notNull(cFillingFacilit, "设备不存在");

        //查询临时用户单价
        List<CUnitPrice> cUnitPrice = cUnitPriceService.selectCUnitPriceList(new CUnitPrice());
        Assert.notNull(cUnitPrice, "单价不存在");
        Integer price = cFillingFacilit.getUnitTemporary();
        Assert.notNull(price, "加注机未设置单价");
        System.out.println("临时加注单价" + price + "支付金额" + orderMoney);
        //计算加注量
        Double vol = fillService.calculateFillVol(Integer.valueOf(orderMoney), price);

        //转换总金额
        Double orderMoneyInt = Double.valueOf(Integer.valueOf(orderMoney) / 100);
        //转换单价
        Double priceInt = Double.valueOf(price) / 100;
        //构建下单对象
        System.out.println("量" + vol + "总金额" + orderMoneyInt + "转换单价" + priceInt );
        if (vol * priceInt != orderMoneyInt) {
            return AjaxResult.error("所加容量和总价不匹配");
        }


        PayOrderDTO payOrderDTO = new PayOrderDTO();
        payOrderDTO.setSn(facilitId);
        payOrderDTO.setOrderVol(vol);
        payOrderDTO.setOrderPrice(priceInt);
        payOrderDTO.setOrderMoney(orderMoneyInt);
        payOrderDTO.setSnNumber(snNumber);


        String payDtoJson = JSONObject.toJSONString(payOrderDTO);


        JsApiOrderModel jsApiOrderModel = new JsApiOrderModel();
        String randomStr = generateRandomString(16);
        String orderNumber = OrderNumberGenerator.generateOrderNumber();
        jsApiOrderModel.setBody("加注订单");
        jsApiOrderModel.setNonce_str(randomStr);
        jsApiOrderModel.setOut_trade_no(orderNumber);
        jsApiOrderModel.setTotal_fee(orderMoney);
        jsApiOrderModel.setOpenid(userOpenid);
        jsApiOrderModel.setNotify_url("https://zsky.lytx.net.cn/api/Filer/payCallback");
//        jsApiOrderModel.setNotify_url("http://124.70.218.167:33389/api/Filer/payCallback");
        jsApiOrderModel.setAttach(payDtoJson);
        JSONObject payment = new Payment().paymentPay(jsApiOrderModel);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("data", payment);
        ajaxResult.put("orderNumber", orderNumber);
        System.out.println("=======支付信息==========");
        System.out.println(payment);
        System.out.println("=======支付信息==========");
        return ajaxResult;
    }

    //钱包充值
    @ApiOperation("钱包充值")
    @PostMapping("/wallet")
    public AjaxResult wallet(@ApiParam(value = "userOpenid", required = true) String userOpenid,
                             @ApiParam(value = "支付金额", required = true) String orderMoney) {
        JsApiOrderModel jsApiOrderModel = new JsApiOrderModel();
        String randomStr = generateRandomString(16);
        String orderNumber = OrderNumberGenerator.generateOrderNumber();
        jsApiOrderModel.setBody("钱包充值");
        jsApiOrderModel.setNonce_str(randomStr);
        jsApiOrderModel.setOut_trade_no(orderNumber);
        jsApiOrderModel.setTotal_fee(orderMoney);
        jsApiOrderModel.setOpenid(userOpenid);
        jsApiOrderModel.setNotify_url("https://zsky.lytx.net.cn/api/wallet/recharge-person-wallet-callback");
//        jsApiOrderModel.setNotify_url("http://124.70.218.167:33389/api/wallet/recharge-person-wallet-callback");
        JSONObject payment = new Payment().paymentPay(jsApiOrderModel);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("data", payment);
        return ajaxResult;
    }

    //微信下单支付状态查询
    @ApiOperation("微信下单支付状态查询")
    @RecordOpeate(desc = "微信下单")
    @PostMapping("/queryOrder")
    public AjaxResult queryOrder(@ApiParam(value = "订单号", required = true) String orderNumber) {
        String queryOrder = new Payment().queryOrder(orderNumber);
//        转为map
        Map<String, String> stringStringMap = WxPayKit.xmlToMap(queryOrder);
        String trade_state_desc = stringStringMap.get("trade_state_desc");
        String out_trade_no = stringStringMap.get("out_trade_no");
        String id = redisCache.getCacheObject("fillOrderId:" + out_trade_no);

        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("trade_state_desc", trade_state_desc);
        ajaxResult.put("out_trade_no", out_trade_no);
        ajaxResult.put("id", id);
        return ajaxResult;
    }


    //强制退款
    @ApiOperation("强制退款")
    @PostMapping("/hard-refund")
    public AjaxResult refund(@ApiParam(value = "订单号", required = true) String orderNumber,
                             @ApiParam(value = "订单总金额", required = true) Integer Totalfee,
                             @ApiParam(value = "退款金额", required = true) Integer refundFee) {
        // 调用 RefundService
        return refundService.processRefund(orderNumber, Totalfee, refundFee);
    }

}
